package controller.admin;
import Message.entity.Employee;
import Message.Result;
import Message.DTO.UpdatePasswordDTO;
import Message.vo.PageBeanVO;
import constant.JwtClaimsConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import properties.JwtProperties;
import service.EmployeeService;
import utils.JwtUtil;
import Message.vo.EmployeeLoginVO;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import io.jsonwebtoken.Claims;
@Slf4j
@RequestMapping("/admin/employee")
@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 登录
     * @return
     */

    @PostMapping("/login")
    public Result login(@RequestBody Employee employeeLoginDTO) throws Exception {
        log.info("员工登录：{}", employeeLoginDTO);
        // 调用service进行登录验证
        Employee loginEmployee = employeeService.login(employeeLoginDTO);
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, loginEmployee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(loginEmployee.getId())
                .userName(loginEmployee.getUsername())
                .name(loginEmployee.getName())
                .token(token)
                .build();
        return Result.success(employeeLoginVO);
    }
    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    public Result logout() {
        return Result.success();
    }
    /**
     *新增用户
     */
      @PostMapping("")
    public Result addEmp( @RequestBody Employee Emp){
          log.info("员工新增：{}", Emp);
          boolean ok = employeeService.addEmp(Emp);
          if (ok) {
              return Result.success();
          } else {
              return Result.error("新增失败");
          }
      }
    /**
     *
     *
     *回显员工
     *
     */
    @GetMapping("/{id}")
    public Result getEmpById(@PathVariable long id){

        log.info("回显",id);
        Employee emp = employeeService.getEmpById(id);
        return Result.success(emp);
    }
    /**
     *
     *员工修改密码
     *
     */
    @PutMapping("/editPassword")
    public Result editPassword(@RequestBody UpdatePasswordDTO updatePassword, HttpServletRequest request) throws Exception {
        log.info("员工修改密码：{}", updatePassword);

        // 从请求头获取token，优先使用配置的管理端token名，其次尝试Authorization: Bearer <token>
        String tokenHeaderName = jwtProperties.getAdminTokenName();
        String token = request.getHeader(tokenHeaderName);
        if (token == null || token.trim().isEmpty()) {
            String authHeader = request.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                token = authHeader.substring(7);
            }
        }

        if (token == null || token.trim().isEmpty()) {
            log.error("未提供有效的认证令牌");
            return Result.error("未提供有效的认证令牌");
        }

        // 解析token，获取员工ID
        Long empId;
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Object empIdObj = claims.get(JwtClaimsConstant.EMP_ID);
            if (empIdObj == null) {
                log.error("令牌中缺少员工ID");
                return Result.error("令牌无效：缺少员工ID");
            }
            if (empIdObj instanceof Number) {
                empId = ((Number) empIdObj).longValue();
            } else if (empIdObj instanceof String) {
                empId = Long.valueOf((String) empIdObj);
            } else {
                empId = Long.valueOf(String.valueOf(empIdObj));
            }
        } catch (Exception e) {
            log.error("解析令牌失败", e);
            return Result.error("令牌无效或已过期");
        }

        // 将token中的员工ID注入到更新对象中
        updatePassword.setEmpId(empId);

        if (updatePassword.getOldPassword() == null || updatePassword.getOldPassword().trim().isEmpty()) {
            log.error("旧密码不能为空");
            return Result.error("旧密码不能为空");
        }
        
        if (updatePassword.getNewPassword() == null || updatePassword.getNewPassword().trim().isEmpty()) {
            log.error("新密码不能为空");
            return Result.error("新密码不能为空");
        }
        Object result = employeeService.editPassword(updatePassword);
        return Result.success(result);
    }
    /**
     * 员工分页查询
     * @param pageBean 分页查询参数
     * @return 分页查询结果
     */
    @GetMapping("/page")
    public Result page(PageBeanVO pageBean) {
        log.info("员工分页查询：{}", pageBean);
        return employeeService.SelectPage(pageBean);
    }
    @PutMapping()
    public Result updateEmp(@RequestBody Employee emp) {

        log.info("员工信息{}",emp);
        employeeService.updateEmp(emp);
        return Result.success();

    }

    @PostMapping("/status/{status}")
    public Result updateEmpStatus(@PathVariable Integer status,long id) {

        log.info("员工禁用{}",status,id);
        //把status,id 两个参数传入服务层
        employeeService.updateEmpStatus(status,id);
        return Result.success();


    }










}
